/**
 * @file rooms.py
 * @brief Room-related API routes for Meeting Management System.
 * @author Ziyi Wang
 *
 * Provides meeting room CRUD, search, and admin endpoints.
 */
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Dict, Any
from sqlalchemy import func
from pydantic import BaseModel

from ..database import get_db
from ..models.schemas import Room, RoomCreate, RoomUpdate
from ..models.models import Room as RoomModel
from ..auth import get_current_active_user, get_admin_user
from ..models.models import User as UserModel

# 定义响应模型
class RoomListResponse(BaseModel):
    rooms: List[Room]
    total: int
    
    model_config = {"from_attributes": True}

router = APIRouter(
    prefix="/api/rooms",
    tags=["rooms"],
    responses={404: {"description": "Not found"}},
)

/**
 * @brief Create a new meeting room (admin only).
 * @param room RoomCreate schema
 * @param db Database session
 * @param current_user Current admin user
 * @return Created room
 * @exception HTTPException 400 if room name exists
 */
# 创建新会议室 (仅管理员可操作)
@router.post("/", response_model=Room, status_code=status.HTTP_201_CREATED)
def create_room(
    room: RoomCreate, 
    db: Session = Depends(get_db), 
    current_user: UserModel = Depends(get_admin_user)
):
    db_room = db.query(RoomModel).filter(RoomModel.name == room.name).first()
    if db_room:
        raise HTTPException(status_code=400, detail="会议室名称已存在")
    
    db_room = RoomModel(**room.model_dump())
    db.add(db_room)
    db.commit()
    db.refresh(db_room)
    return db_room

/**
 * @brief Get all available meeting rooms (with search and pagination).
 * @param skip Offset
 * @param limit Limit
 * @param search Search keyword
 * @param capacity Capacity filter
 * @param db Database session
 * @param current_user Current user
 * @return List of rooms and total count
 */
# 获取所有会议室
@router.get("/", response_model=RoomListResponse)
def read_rooms(
    skip: int = 0, 
    limit: int = 100,
    search: str = "",
    capacity: str = "",
    db: Session = Depends(get_db), 
    current_user: UserModel = Depends(get_current_active_user)
):
    # 基础查询：只查询可用的会议室
    query = db.query(RoomModel).filter(RoomModel.is_active == True)
    
    # 按名称或位置搜索
    if search:
        query = query.filter(
            (RoomModel.name.contains(search)) | 
            (RoomModel.location.contains(search)) | 
            (RoomModel.facilities.contains(search))
        )
    
    # 按容量筛选
    if capacity:
        if capacity.startswith('exact:'):
            # 精确匹配容量
            try:
                exact_capacity = int(capacity.split(':')[1])
                query = query.filter(RoomModel.capacity >= exact_capacity)
            except (ValueError, IndexError):
                pass
        elif capacity == "1-5":
            query = query.filter(RoomModel.capacity >= 1, RoomModel.capacity <= 5)
        elif capacity == "6-10":
            query = query.filter(RoomModel.capacity >= 6, RoomModel.capacity <= 10)
        elif capacity == "11-20":
            query = query.filter(RoomModel.capacity >= 11, RoomModel.capacity <= 20)
        elif capacity == "21+":
            query = query.filter(RoomModel.capacity >= 21)
    
    # 获取总记录数
    total = query.count()
    
    # 应用分页
    rooms = query.offset(skip).limit(limit).all()
    
    # 创建响应对象
    return RoomListResponse(rooms=rooms, total=total)

/**
 * @brief Get a specific meeting room by ID.
 * @param room_id Room ID
 * @param db Database session
 * @param current_user Current user
 * @return Room info
 * @exception HTTPException 404 if not found
 */
# 获取指定会议室
@router.get("/{room_id}", response_model=Room)
def read_room(
    room_id: int, 
    db: Session = Depends(get_db), 
    current_user: UserModel = Depends(get_current_active_user)
):
    db_room = db.query(RoomModel).filter(RoomModel.id == room_id).first()
    if db_room is None:
        raise HTTPException(status_code=404, detail="会议室不存在")
    return db_room

/**
 * @brief Update meeting room info (admin only).
 * @param room_id Room ID
 * @param room RoomUpdate schema
 * @param db Database session
 * @param current_user Current admin user
 * @return Updated room
 * @exception HTTPException 404 if not found, 400 if name exists
 */
# 更新会议室信息 (仅管理员可操作)
@router.put("/{room_id}", response_model=Room)
def update_room(
    room_id: int, 
    room: RoomUpdate, 
    db: Session = Depends(get_db), 
    current_user: UserModel = Depends(get_admin_user)
):
    db_room = db.query(RoomModel).filter(RoomModel.id == room_id).first()
    if db_room is None:
        raise HTTPException(status_code=404, detail="会议室不存在")
    
    # 检查名称唯一性
    if room.name and room.name != db_room.name:
        existing_room = db.query(RoomModel).filter(RoomModel.name == room.name).first()
        if existing_room:
            raise HTTPException(status_code=400, detail="会议室名称已存在")
    
    # 更新字段
    room_data = room.model_dump(exclude_unset=True)
    for key, value in room_data.items():
        setattr(db_room, key, value)
    
    db.commit()
    db.refresh(db_room)
    return db_room

/**
 * @brief Delete a meeting room (admin only, soft delete).
 * @param room_id Room ID
 * @param db Database session
 * @param current_user Current admin user
 * @return None
 * @exception HTTPException 404 if not found
 */
# 删除会议室 (仅管理员可操作)
@router.delete("/{room_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_room(
    room_id: int, 
    db: Session = Depends(get_db), 
    current_user: UserModel = Depends(get_admin_user)
):
    db_room = db.query(RoomModel).filter(RoomModel.id == room_id).first()
    if db_room is None:
        raise HTTPException(status_code=404, detail="会议室不存在")
    
    # 软删除：将is_active设置为False
    db_room.is_active = False
    db.commit()
    return None

/**
 * @brief Get all rooms (including inactive, admin only).
 * @param skip Offset
 * @param limit Limit
 * @param db Database session
 * @param current_user Current admin user
 * @return List of all rooms
 */
# 获取所有会议室（包括非活跃的，仅管理员可见）
@router.get("/admin/all", response_model=List[Room])
def read_all_rooms(
    skip: int = 0, 
    limit: int = 100, 
    db: Session = Depends(get_db), 
    current_user: UserModel = Depends(get_admin_user)
):
    rooms = db.query(RoomModel).offset(skip).limit(limit).all()
    return rooms